#include "../UI/MainWindow.hpp"
#include "../src/ConfigLoad.hpp"
#include "../src/HandleResultModel.hpp"
#include "../src/OriginImageModel.hpp"
#include "ImageType.hpp"
#include <chrono>
#include <iostream>
#include <thread>

MainWindow *mainWindow = nullptr;

bool refreshClock = true;

struct ImgObject {
  int index;
};

std::map<std::string, ImgObject> ImageMap;

void Handle_NewImage(const std::vector<ImageType> &image) {
  for (auto &i : image) {
    auto ptr = ImageMap.find(i.uuid);
    if (ptr != ImageMap.end())
      mainWindow->SetNewImage(i.width, i.height, i.data, ptr->second.index);
    else
      std::cout << "can't find image id " << i.uuid << std::endl;
  }
}

int main() {
  ConfigLoad config;
  std::mutex InitMut;
  InitMut.lock();
  HandleResultModel handleresult;
  handleresult.Boot([&](const ImageType &img) {
    if (mainWindow == nullptr)
      return;
    mainWindow->SetNewImage(img.width, img.height, img.data, 0);
  });
  std::thread UIThread([&]() {
    auto app = Gtk::Application::create("org.gtkmm.BigScreen.test");
    MainWindow mainUI;
    app->signal_activate().connect([&]() {
      app->add_window(mainUI);
      mainUI.set_visible(true);
      mainWindow = &mainUI;
      InitMut.unlock();
    });
    app->run();
    mainWindow = nullptr;
  });
  InitMut.lock();
  ImageMap = {{"C1527A0090488", {1}},
              {"C1527A0090431", {2}},
              {"C1527A0090503", {3}},
              {"C1527A0090416", {4}},
              {"C1527A0090539", {5}}};
  OriginImageModel oriImage(config.GetCameraIDList(), config.GetShmSize(),
                            Handle_NewImage);
  std::thread clockThread([&]() {
    while (refreshClock) {
      std::this_thread::sleep_for(std::chrono::milliseconds(30));
      if (mainWindow != nullptr)
        mainWindow->refreshUI();
    }
  });
  oriImage.Boot();
  try {
    refreshClock = false;
    UIThread.join();
    clockThread.join();
  } catch (const std::exception &e) {
    std::cout << e.what() << std::endl;
  }
}
